package calculater;

import java.awt.Color;
import java.awt.Font;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class Calculater {
	
	private JFrame frame = new JFrame("Vincent Chua的计算器");
	private JTextArea textArea = new JTextArea(2, 18);
	private String input = new String();
	private JButton e =new JButton("=");
	private JLabel label =new JLabel("a");
	private double result = 0;
	public void init() {
		frame.setLayout( null );
		String[] bn = {" ","DEL"," "," ","÷","1","2","3","+","4","5","6","-","7","8","9","x"," ","0"};
		for( int i=1,j=1,k=1; i<bn.length; i++,j++) {
			ButtonListener bListener = new ButtonListener(bn[i]);
			JButton button = new JButton(""+bn[i]);
			button.addActionListener(bListener);
			button.setFont(new Font("微软雅黑", Font.ITALIC, 35));
			button.setBounds( 130*(j-1), 110*k+130 , 130, 110);
			frame.add(button);
			if( i%4==0 ) {
				j=0;
				k++;
			}
		}
		textArea.setBounds(0, 0, 518, 235);
		textArea.setFont(new Font("微软雅黑", Font.ITALIC, 45));
		textArea.setText("目前仅支持两个\n整数的四则运算\n请先按下DEL后使用");
		e.setBackground(Color.GREEN);
		e.setBounds(260, 680, 260, 110);
		e.addActionListener(new ButtonListener("="));
		frame.add(e);
		frame.add(label);
		frame.add(textArea);
		frame.setBounds(150, 150, 525, 830);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setResizable(false);
		frame.setVisible(true);
	}
	
	class ButtonListener implements ActionListener{
		private String button_input;
		public ButtonListener(String button_input) {
			this.button_input = button_input;
		}
		
		public void actionPerformed(ActionEvent e) {
			textArea.append(button_input);
			if( button_input.equals("DEL") ) {
				textArea.setText("");
				input ="";
			}
			else if( button_input.equals("=")){
				textArea.append(computer(input));
				input ="";
			}
			else {
				input+=button_input; 
			}
		}
		
		private boolean subs(String input,String cal) {
			int n1 = 0;
			int n2 = 0;
			boolean b = false;
			if( input.indexOf(cal)!=-1 ) {
				b=true;
				n1 = Integer.parseInt(input.substring(0, input.indexOf(cal)));
				n2 = Integer.parseInt(input.substring(input.indexOf(cal)+1, input.length() ) );
				if( cal.equals("+") ) {
					result = n1+n2;
				}
				else if( cal.equals("-") ) {
					result = n1-n2;
				}
				else if( cal.equals("x") ) {
					result =n1*n2;
				}
				else if( cal.equals("÷") ) {
					if( n2!=0 ) {
						result =n1/n2;
					}
					else {
						b=false;
					}
				}
			}
			return b;
		}
		
		private String computer(String input) {
			String ret = "";
			if( subs(input, "+") || subs(input, "-") || subs(input, "x") || subs(input, "÷")) {
				ret = result+"";
			}
			else {
				ret = "错误";
			}
			return ret;
		}
	}
	
	public static void main(String[] args) {
		new Calculater().init();
	}

}
